﻿#include "logindemo.h"
#include "ui_logindemo.h"
#include "ini_file.h"
#include <QMessageBox>
#include <QByteArray>
#include <QString>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonParseError>
#include <QJsonValue>
#include <QJsonObject>
#include <QDebug>
#include <iostream>
#include <QUrlQuery>
#include <QtNetwork>
#include<QDir>
//
LoginDemo::LoginDemo(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginDemo)
{
    ui->setupUi(this);
    //setWindowTitle("Login");
    ui->com_check->setCurrentIndex(INI_File().GetMode());

    ui->line_serverAddr->setText(INI_File().GetServerIP());
    ui->line_username->setText(INI_File().GetUserName());
    ui->line_pwd->setText(INI_File().GetPassWord());

    setWindowTitle(INI_File().GetTitle());
    qDebug()<< u8"标题:" + INI_File().GetTitle();

}

LoginDemo::~LoginDemo()
{
    delete ui;
}

// 确认按钮
void LoginDemo::on_btn_ok_clicked()
{


}


//完成请求
void LoginDemo::finishRequest(QNetworkReply *reply)
{
    if (reply->error()){
        qDebug()<<"Error!"<<endl;
        return;
    }else{
        //解析reply中携带的Json
        QByteArray byte_array = reply->readAll();  //Json ducument
        QJsonParseError json_error;
        QJsonDocument parse_document = QJsonDocument::fromJson(byte_array, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            if(parse_document.isObject())
            {
                QJsonObject obj = parse_document.object();
                if(obj.contains("code"))
                {
                    QJsonValue code_value = obj.take("code");
                    QString code_value_string = code_value.toString();
                    qInfo()<< "code:" +  code_value_string;

                    if(code_value_string == "01")
                    {
                        ui->label_msg->setText(u8"校验成功!");
                        qInfo()<<u8"校验成功!";
                        //QJsonValue token = obj.take("token");
                    }
                    else
                    {
                        QJsonValue message_value = obj.take("err");
                        QString error_message = message_value.toString();
                        ui->label_msg->setText(error_message);
                        //ui->line_username->clear();
                        //ui->line_pwd->clear();
                        qInfo()<<error_message;
                    }
                }
            }
        }
    }
    reply->deleteLater();
}

//共享端口-多选框
void LoginDemo::on_check_prot_stateChanged(int arg1)
{
    qDebug()<<u8"共享端口-多选框" + QString::number(arg1);

    if(2 == arg1)
    {
        ui->line_directory->setDisabled(false);
    }
    else
    {
        ui->line_directory->setDisabled(true);
    }

}

//校验按钮
void LoginDemo::on_btn_check_clicked()
{
    ui->label_msg->clear();
    INI_File().SetServerIP(ui->line_serverAddr->text());
    QString username = ui->line_username->text();
    QString password = ui->line_pwd->text();
    int Mode = INI_File().GetMode();

    QString joinUrl;
    QUrlQuery urlQuery;
    if(Mode == 0 && (username.isEmpty() || password.isEmpty()))
    {
        //QMessageBox::warning(this,u8"警告",u8"用户名或者密码为空!",QMessageBox::Yes);
        ui->label_msg->setText(u8"用户名或者密码为空!");
        ui->line_username->clear();
        ui->line_pwd->clear();
        return;
    }
    else
    {
        switch (Mode)
        {
        case 1 :
            //MAC校验方式
            joinUrl = INI_File().GetPortAuthByMac();
            urlQuery.addQueryItem("mac",username);
            break;

        case 2:
            //IP校验方式
            joinUrl = INI_File().GetPortAuthByIP();
            urlQuery.addQueryItem("IP",username);
            urlQuery.addQueryItem("mac",INI_File().GetMac());

            break;
        case 3:
            //域用户校验方式
            joinUrl = INI_File().GetPortAuthByDomainUser();
            urlQuery.addQueryItem("mac",INI_File().GetMac());
            urlQuery.addQueryItem("domain",getlocalHostName());
            urlQuery.addQueryItem("domainUser",getlocalName());

            break;
        default:
            //用户名
            joinUrl = INI_File().GetPortLoginUser();
            urlQuery.addQueryItem("username",username);
            urlQuery.addQueryItem("pwd",password);
            urlQuery.addQueryItem("mac",INI_File().GetMac());

            break;
        }

        QString baseUrl = QString("http://%1%2").arg(INI_File().GetServerIP()).arg(joinUrl);//"http:"不要少
        QUrl url(baseUrl);
        url.setQuery(urlQuery);
        qInfo()<<"url:" + url.toString();
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");  //上面语句固定这么写，要不然会报错“contest—type is missing”
        request.setUrl(url);
        //manager发送请求，并接收reply，委托给slot处理
        manager.get(request);
        connect(&manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(finishRequest(QNetworkReply*)));
    }

}

void LoginDemo::on_com_check_currentIndexChanged(int index)
{
    QString Mac = getMAC();
    INI_File().SetMode(index);
    QString domainUser = QString("%1/%2").arg(getlocalHostName()).arg(getlocalName());
    switch (index)
    {
    case 1 :
        //MAC校验方式
        selectMode();

        INI_File().SetMac(Mac);
        ui->line_username->setText(Mac);
        break;
    case 2:
        //IP校验方式
        selectMode();
        INI_File().SetMac(getMAC());
        ui->line_username->setText(getIP());

        break;
    case 3:
        //域用户校验方式
        selectMode();     
        ui->line_username->setText(domainUser);

        break;
    default:
        //用户名
        ui->line_username->clear();
        ui->line_username->setDisabled(false);
        ui->line_pwd->clear();
        ui->line_pwd->setDisabled(false);

        break;
    }

    //qInfo()<< u8"选择了" + QString::number(index);
}

void LoginDemo::selectMode()
{
    ui->line_username->setDisabled(true);
    ui->line_username->clear();
    ui->line_pwd->setDisabled(true);
    ui->line_pwd->clear();
}

QString LoginDemo::getIP() //获取ip地址
{

    //    QString strIpAddress;
    //    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    //    // 获取第一个本主机的IPv4地址
    //    int nListSize = ipAddressesList.size();
    //    for (int i = 0; i < nListSize; i++)
    //    {
    //           if (ipAddressesList.at(nListSize-1) != QHostAddress::LocalHost &&
    //               ipAddressesList.at(nListSize-1).toIPv4Address()) {
    //               strIpAddress = ipAddressesList.at(nListSize-1).toString();
    //               break;
    //           }
    //     }
    //     // 如果没有找到，则以本地IP地址为IP
    //     if (strIpAddress.isEmpty())
    //        strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();
    //     return strIpAddress;

    //获取主机名
    QString localHostName = QHostInfo::localHostName();
    //获取本机的IP地址(可能有多条）
    QHostInfo info = QHostInfo::fromName(localHostName);
    QList<QHostAddress> addrList = info.addresses();

    return  addrList.at(addrList.size()-1).toString();
}

QString LoginDemo::getMAC() //获取Mac地址
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";

//    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
//    //获取所有网络接口的列表
//    foreach(QNetworkInterface interface,list)
//    {
//        //遍历每一个网络接口
//        qDebug() << "Device: "<<interface.name();

//        //设备名
//        qDebug() << "HardwareAddress:"<<interface.hardwareAddress();

//        //硬件地址
//        QList<QNetworkAddressEntry> entryList = interface.addressEntries();

//        //获取IP地址条目列表，每个条目中包含一个IP地址，一个子网掩码和一个广播地址
//        foreach(QNetworkAddressEntry entry,entryList)
//        {
//            //遍历每一个IP地址条目
//            qDebug()<<"IP Address: "<<entry.ip().toString();

//            //子网掩码
//            qDebug()<<"Netmask: "<<entry.netmask().toString();

//            //广播地址
//            qDebug()<<"Broadcast: "<<entry.broadcast().toString();

//            qDebug()<<endl;
//        }
//    }

    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }

    return strMacAddr;
}
//获取主机名
QString LoginDemo::getlocalHostName()
{
  QString localHostName = QHostInfo::localHostName();
  return localHostName;
}
//获取当前登录用户名
QString LoginDemo::getlocalName()
{
    QString localName = QDir::home().dirName();
    //qDebug()<<localName;
    return localName;
}
